package vip.xiaonuo.smzq.modular.nbfb.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.enums.WriteDirectionEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import vip.xiaonuo.auth.core.pojo.SaBaseLoginUser;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.smzq.core.gson.GsonUtil;
import vip.xiaonuo.smzq.core.tools.file.PathUtils;
import vip.xiaonuo.smzq.core.utils.StringUtilTool;
import vip.xiaonuo.smzq.modular.deom.ToolData;
import vip.xiaonuo.smzq.modular.deom.TypeProcessing;
import vip.xiaonuo.smzq.modular.dictionary.entity.Cb06Kc;
import vip.xiaonuo.smzq.modular.dictionary.mapper.Cb06KcMapper;
import vip.xiaonuo.smzq.modular.dictionary.mapper.Cb08XzqhMapper;
import vip.xiaonuo.smzq.modular.hisi.entity.vo.KcdgmtjVo;
import vip.xiaonuo.smzq.modular.hisi.service.IHisiKsService;
import vip.xiaonuo.smzq.modular.kcl.entity.Zycl;
import vip.xiaonuo.smzq.modular.nbfb.entity.param.NbfbSixParam;
import vip.xiaonuo.smzq.modular.nbfb.entity.vo.NbfbFourData;
import vip.xiaonuo.smzq.modular.nbfb.entity.vo.NbfbFourVo;
import vip.xiaonuo.smzq.modular.nbfb.entity.vo.NbfbSixVo;
import vip.xiaonuo.smzq.modular.nbfb.mapper.ZyclSixMapper;
import vip.xiaonuo.smzq.modular.nbfb.service.INbfbSixService;
import vip.xiaonuo.smzq.modular.user.entity.Role;
import vip.xiaonuo.smzq.modular.user.mapper.RoleMapper;
import vip.xiaonuo.sys.modular.role.enums.SysRoleEnum;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class NbfbSixServiceImpl extends ServiceImpl<ZyclSixMapper, Zycl> implements INbfbSixService {
    @Resource
    private ZyclSixMapper zyclSixMapper;
    @Resource
    private IHisiKsService iHisiKsService;

    @Resource
    private RoleMapper roleMapper;
    @Resource
    private Cb08XzqhMapper cb08XzqhMapper;
    @Resource
    private Cb06KcMapper cb06KcMapper;

    @Value("${file.base}")
    String baseFilePath;

    public List<NbfbSixVo> getNbfbSixold(NbfbSixParam param) {
        List<NbfbSixVo> nbfbSixVoList = new ArrayList<>();
        Integer nd = param.getNd();
        String kcdmStr = param.getKcdm();
        List<String> list = Arrays.asList(kcdmStr.split(","));
        //查询年度附表6数据
        List<Map> maps = new ArrayList<>();

        //获取用户信息
        SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
        Role role = roleMapper.selectById(saBaseLoginUser.getPositionId());
        List<Map> xzqhList = new ArrayList<>();


        if (SysRoleEnum.ADMIN.getValue().equals(role.getCode()) || SysRoleEnum.BJSH.getValue().equals(role.getCode()) || SysRoleEnum.SHENGSH.getValue().equals(role.getCode())) {
            xzqhList = cb08XzqhMapper.getShengXzqhList(130000);
            maps = zyclSixMapper.getShiGm(nd);
        } else if (SysRoleEnum.SHISH.getValue().equals(role.getCode())) {
            Integer xkzh = Integer.valueOf(saBaseLoginUser.getDirectorId());
            xzqhList = cb08XzqhMapper.getShiXzqhList(xkzh);
            maps = zyclSixMapper.getGm(nd);
        } else if (SysRoleEnum.XIANSH.getValue().equals(role.getCode())) {
            Integer xkzh = Integer.valueOf(saBaseLoginUser.getDirectorId());
            xzqhList = cb08XzqhMapper.getXianXzqhList(xkzh);
            maps = zyclSixMapper.getGm(nd);

        }

        for (String kcdm : list) {
            NbfbSixVo nbfbSixVo = new NbfbSixVo();
            List<Integer> kzbhList = TypeProcessing.strToList(kcdm);
            List<KcdgmtjVo> kcdmList = new ArrayList<>();

                if (kzbhList != null && kzbhList.size() == 3) {
                    LambdaQueryWrapper<Cb06Kc> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(Cb06Kc::getKcdm, kzbhList.get(1));
                    wrapper.eq(Cb06Kc::getTjdx, kzbhList.get(2));
                    Cb06Kc cb06Kc = cb06KcMapper.selectOne(wrapper);
                    if (cb06Kc != null){
                        if (cb06Kc.getXsbs()==0){
                            nbfbSixVo.setDw(cb06Kc.getJsldw());
                        }else if (cb06Kc.getXsbs()==1){
                            nbfbSixVo.setDw(cb06Kc.getKsldw());
                        }

                        if (cb06Kc.getJsdxmc()!=null&& !cb06Kc.getJsdxmc().equals("")){
                            nbfbSixVo.setKcmc(cb06Kc.getKcmc() + " (" + cb06Kc.getJsdxmc() + ")");
                        }else{
                            nbfbSixVo.setKcmc(cb06Kc.getKcmc());
                        }

                    }

                kcdmList=   getKcdgmtjListNew(xzqhList, kzbhList.get(1), kzbhList.get(2), maps,nbfbSixVo.getDw());

            }
            if (kcdmList.size() > 0){
                nbfbSixVo.setKcdgmtjList(kcdmList);
                nbfbSixVoList.add(nbfbSixVo);
            }


        }
        return nbfbSixVoList;
    }

    @Override
    public List<NbfbSixVo> getNbfbSix(NbfbSixParam param) {
        String[] array = {"42201", "42202", "32006", "63701"};
        List<NbfbSixVo> nbfbSixVoList = new ArrayList<>();
        //特殊矿种特殊分类
        List<NbfbSixVo> tsvoList = new ArrayList<>();
        Integer nd = param.getNd();
        String kcdmStr = param.getKcdm();
       // List<String> list = Arrays.asList(kcdmStr.split(","));
        //查询年度附表6数据
        List<KcdgmtjVo> nbfbSixList =new ArrayList<>();

        //获取用户信息
        SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
        Role role = roleMapper.selectById(saBaseLoginUser.getPositionId());

        if (SysRoleEnum.ADMIN.getValue().equals(role.getCode()) || SysRoleEnum.BJSH.getValue().equals(role.getCode()) || SysRoleEnum.SHENGSH.getValue().equals(role.getCode())) {
            nbfbSixList = zyclSixMapper.getNbfbsix(nd);
        }

        if (nbfbSixList.size()==0){
           return nbfbSixVoList;
        }


        //根据矿种分组
        Map<String, List<KcdgmtjVo>> groupMap = nbfbSixList.stream().collect(Collectors.groupingBy(KcdgmtjVo::getBz));
        for (Map.Entry<String, List<KcdgmtjVo>> entry : groupMap.entrySet()) {
            NbfbSixVo vo = new NbfbSixVo();
            List<KcdgmtjVo> sixList = entry.getValue();
            String bz = entry.getKey();
            String kcdm = StringUtilTool.extractMiddlePart(bz);
            if (kcdmStr != null && !kcdmStr.equals("")) {
                //是否包含特殊矿种
                if (Arrays.toString(array).contains(kcdm) && kcdmStr.contains(kcdm)) {
                    if (CollectionUtil.isNotEmpty(sixList)) {
                        vo.setBz(sixList.get(0).getBz());
                        vo.setKcmc(sixList.get(0).getKcmc());
                        vo.setDw(sixList.get(0).getDw());
                    }
                    List<KcdgmtjVo> dataList = GsonUtil.ObjectToList(sixList, KcdgmtjVo.class);
                    vo.setKcdgmtjList(dataList);
                    tsvoList.add(vo);
                } else {
                    if (kcdmStr.contains(bz)) {
                        if (CollectionUtil.isNotEmpty(sixList)) {
                            vo.setBz(sixList.get(0).getBz());
                            vo.setKcmc(sixList.get(0).getKcmc());
                            vo.setDw(sixList.get(0).getDw());
                        }
                        List<KcdgmtjVo> dataList = GsonUtil.ObjectToList(sixList, KcdgmtjVo.class);
                        vo.setKcdgmtjList(dataList);
                        nbfbSixVoList.add(vo);
                    }
                }
            }
        }
        nbfbSixVoList.addAll(tsvoList);
    // 根据 getBz() 方法的结果对列表进行排序
        return nbfbSixVoList.stream()
                .sorted(Comparator.comparing(NbfbSixVo::getBz))
            .collect(Collectors.toList());
    }


    /**
     * 根据行政区划，矿产名称，统计对象名称，过滤数据
     */
    public List<KcdgmtjVo> getKcdgmtjListNew(List<Map> xzqhList, Integer kcmc, Integer jsdxmc, List<Map> kcdmList,String dw) {
        List<KcdgmtjVo> kcdgmtjVoList = new ArrayList<>();
        for (Map map : xzqhList) {
            String xzqdm = map.get("dm").toString();
            String xzqhmc = (String) map.get("mc");
            String bjzd = "";
            if (kcmc != null) {
                bjzd = kcmc + "_";
            }
            if (jsdxmc != null) {
                bjzd += jsdxmc + "_";
            }
            if (xzqhmc != null) {
                bjzd += xzqdm.replaceAll("0+$", "");
            }
            KcdgmtjVo kcdgmtjVo = new KcdgmtjVo();
            int biggmcount = 0;
            Double bigbyl=0.0;
            Double bigbyjsl=0.0;
            Double bigbyksl=0.0;
            int mingmcount = 0;
            Double minbyl=0.0;
            Double minbyjsl=0.0;
            Double minbyksl=0.0;
            int smagmcount = 0;
            Double smabyl=0.0;
            Double smabyjsl=0.0;
            Double smabyksl=0.0;
            for (Map mapkcgm : kcdmList) {
                String gmbj = "";
                if (mapkcgm.get("kcdm") != null) {
                    gmbj = mapkcgm.get("kcdm") + "_";
                }
                if (mapkcgm.get("tjdx") != null) {
                    gmbj += mapkcgm.get("tjdx") + "_";
                }
                if (mapkcgm.get("xzqdm") != null) {
                    gmbj += mapkcgm.get("xzqdm");
                }

                if (gmbj.contains(bjzd)){

                    if ("大型".equals(mapkcgm.get("gmtype"))){
                        if (mapkcgm.get("gmcount")!=null){
                            biggmcount+=Integer.parseInt(String.valueOf(mapkcgm.get("gmcount")));
                            if (mapkcgm.get("byl")!=null) {
                                BigDecimal bigDecimalValue = new BigDecimal(String.valueOf(mapkcgm.get("byl")));
                                bigbyl += ToolData.roundToTwoDecimals(bigDecimalValue.doubleValue());
                            }
                            if (mapkcgm.get("byjsl")!=null) {
                                BigDecimal bigDecimalValue = new BigDecimal(String.valueOf(mapkcgm.get("byjsl")));
                                bigbyjsl += ToolData.roundToTwoDecimals(bigDecimalValue.doubleValue());
                            }else{
                                bigbyjsl+=0.0;
                            }
                            if (mapkcgm.get("byksl")!=null) {
                                BigDecimal bigDecimalValue = new BigDecimal(String.valueOf(mapkcgm.get("byksl")));
                                bigbyksl += ToolData.roundToTwoDecimals(bigDecimalValue.doubleValue());
                            }else{
                                bigbyksl+=0.0;
                            }
                        }else{
                            biggmcount+=0;
                            bigbyl+=0.0;
                            bigbyjsl+=0.0;
                            bigbyksl+=0.0;
                        }

                    }
                    if ("中型".equals(mapkcgm.get("gmtype"))){
                        if (mapkcgm.get("gmcount")!=null){
                            mingmcount+=Integer.parseInt(String.valueOf(mapkcgm.get("gmcount")));
                            if (mapkcgm.get("byl")!=null) {
                                BigDecimal bigDecimalValue = new BigDecimal(String.valueOf(mapkcgm.get("byl")));
                                minbyl += ToolData.roundToTwoDecimals(bigDecimalValue.doubleValue());
                            }
                            if (mapkcgm.get("byjsl")!=null) {
                                BigDecimal bigDecimalValue = new BigDecimal(String.valueOf(mapkcgm.get("byjsl")));
                                minbyjsl += ToolData.roundToTwoDecimals(bigDecimalValue.doubleValue());
                            }else {
                                minbyjsl+=0.0;
                            }
                            if (mapkcgm.get("byksl")!=null) {
                                BigDecimal bigDecimalValue = new BigDecimal(String.valueOf(mapkcgm.get("byksl")));
                                minbyksl += ToolData.roundToTwoDecimals(bigDecimalValue.doubleValue());
                            }else{
                                minbyksl+=0.0;
                            }
                        }else{
                            mingmcount+=0;
                            minbyl+=0.0;
                            minbyjsl+=0.0;
                            minbyksl+=0.0;
                        }

                    }
                    if ("小型".equals(mapkcgm.get("gmtype"))){
                        if (mapkcgm.get("gmcount")!=null){
                            smagmcount+=Integer.parseInt(String.valueOf(mapkcgm.get("gmcount")));
                            if (mapkcgm.get("byl")!=null) {
                                BigDecimal bigDecimalValue = new BigDecimal(String.valueOf(mapkcgm.get("byl")));
                                smabyl += ToolData.roundToTwoDecimals(bigDecimalValue.doubleValue());
                            }
                            if (mapkcgm.get("byjsl")!=null) {
                                BigDecimal bigDecimalValue = new BigDecimal(String.valueOf(mapkcgm.get("byjsl")));
                                smabyjsl += ToolData.roundToTwoDecimals(bigDecimalValue.doubleValue());
                            }else{
                                smabyjsl+=0.0;
                            }
                            if (mapkcgm.get("byksl")!=null) {
                                BigDecimal bigDecimalValue = new BigDecimal(String.valueOf(mapkcgm.get("byksl")));
                                smabyksl += ToolData.roundToTwoDecimals(bigDecimalValue.doubleValue());
                            }else{
                                smabyksl+=0.0;
                            }

                        }else{
                            smagmcount+=0;
                            smabyl+=0.0;
                            smabyksl+=0.0;
                            smabyjsl+=0.0;
                        }
                    }
                }


            }
            kcdgmtjVo.setBigCount(biggmcount);
            kcdgmtjVo.setBigNmby(ToolData.roundToTwoDecimals(bigbyl));
            kcdgmtjVo.setBigNmbyjsl(ToolData.roundToTwoDecimals(bigbyjsl));
            kcdgmtjVo.setBigNmbyksl(ToolData.roundToTwoDecimals(bigbyksl));
            kcdgmtjVo.setMediumCount(mingmcount);
            kcdgmtjVo.setMediumNmby(ToolData.roundToTwoDecimals(minbyl));
            kcdgmtjVo.setMediumNmbyjsl(ToolData.roundToTwoDecimals(minbyjsl));
            kcdgmtjVo.setMediumNmbyksl(ToolData.roundToTwoDecimals(minbyksl));
            kcdgmtjVo.setSmallCount(smagmcount);
            kcdgmtjVo.setSmallNmby(ToolData.roundToTwoDecimals(smabyl));
            kcdgmtjVo.setSmallNmbyjsl(ToolData.roundToTwoDecimals(smabyjsl));
            kcdgmtjVo.setSmallNmbyksl(ToolData.roundToTwoDecimals(smabyksl));
            kcdgmtjVo.setDw(dw);
//            kcdgmtjVo.setXzqhdm(xzqdm);
            kcdgmtjVo.setXzqhmc(xzqhmc);
            if (bigbyl!=0||minbyl!=0||smabyl!=0){
                kcdgmtjVoList.add(kcdgmtjVo);
            }


        }


        return kcdgmtjVoList;
    }


    /**
     * 临时规模导出所有矿种的导出Excel
     */
    @Override
    public void exportNbfbSixExcel(NbfbSixParam param, HttpServletResponse response) {
//      //  iHisiKsService.exportAllKcGmExcel(param, response);
//        File tempFile = null;
//try {
//    List<NbfbSixVo> nbfbSixVoList = getNbfbSix(param);
//    String fileName =param.getNd() + "年报报表附表6.xlsx";
//    tempFile = new File(PathUtils.getUpLoadPath(baseFilePath) + File.separator + fileName);
//    //写excel
//    //创建一个ExcelWriter对象
//    ExcelWriter excelWriter = EasyExcel.write(tempFile.getPath(), NbfbSixData.class).build();
//
//    //循环创建sheet
//    for (NbfbSixVo vo : nbfbSixVoList) {
//
//        String sheetName = vo.getKcmc();
//
//        WriteSheet writeSheet = EasyExcel.writerSheet(sheetName).build();
//         List<NbfbSixData> nbfbSixDataList = new ArrayList<>();
//         for (KcdgmtjVo kcdgmtjVo : vo.getKcdgmtjList()){
//             NbfbSixData nbfbSixData = new NbfbSixData();
//             BeanUtil.copyProperties(kcdgmtjVo, nbfbSixData);
//             nbfbSixDataList.add(nbfbSixData);
//         }
//        excelWriter.write(nbfbSixDataList, writeSheet);
//
//    }
//
//    //关闭writer，释放资源
//    excelWriter.finish();
//
//    //将生成的文件发送给客户端
//    IoUtil.write(response.getOutputStream(), true, FileUtil.readBytes(tempFile));
//}catch (Exception e){
//
//    log.error(param.getNd() + "年报报表附表6异常：", e);
//    try {
//        CommonResponseUtil.renderError(response, param.getNd() + "年报报表附表6");
//    } catch (IOException ioException) {
//        ioException.printStackTrace();
//    }
//} finally {
//    FileUtil.del(tempFile);
//}
        exportNbfbSixTemplateExport(param, response);
    }

    /**
     * 根据模版导出年报附表6
     * @author Sqq
     * @param param
     * @param response
     */
    public void exportNbfbSixTemplateExport(NbfbSixParam param, HttpServletResponse response) {
        // 获取数据
        List<NbfbSixVo> nbfbSixVoList = getNbfbSix(param);

        // 设置响应头字符集为UTF-8
        response.setCharacterEncoding("utf-8");



        // 设置响应头，指定下载文件名
        response.setContentType("application/octet-stream; charset=UTF-8");
        try {
            //response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(param.getNd() + "年报报表附表6.xlsx", "UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 加载模板文件
        ClassPathResource classPathResource = new ClassPathResource(PathUtils.getNbfbPath(6));
        InputStream inputStream = null;
        try {
            // 从资源路径获取输入流
            inputStream = classPathResource.getStream();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 创建XSSFWorkbook对象来操作Excel文件
        XSSFWorkbook workbook = null;
        try {
            workbook = new XSSFWorkbook(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 设置第一个sheet的名称
        workbook.setSheetName(0, nbfbSixVoList.get(0).getKcmc());

        // 复制第一个sheet到其他sheet
        for (int i = 1; i < nbfbSixVoList.size(); i++) {
            workbook.cloneSheet(0, nbfbSixVoList.get(i).getKcmc());
        }

        // 将工作簿写入字节数组输出流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            workbook.write(baos);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] bytes = baos.toByteArray();

        // 使用字节数组创建输入流
        InputStream templateStream = new ByteArrayInputStream(bytes); // 使用不同的变量名

        // 使用EasyExcel创建ExcelWriter对象
        ExcelWriter excelWriter = null;
        try {
            excelWriter = EasyExcel.write(response.getOutputStream())
                    .withTemplate(templateStream)
                    .build();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 遍历数据列表
        int index = 0;
        for (NbfbSixVo nbfbSixVo : nbfbSixVoList) {
            index++;
            // 创建WriteSheet对象
            WriteSheet writeSheet = EasyExcel.writerSheet(nbfbSixVo.getKcmc()).build();

            // 构建填充配置
            FillConfig fillConfig = FillConfig.builder()
                    .forceNewRow(true)
                    .direction(WriteDirectionEnum.VERTICAL)
                    .build();

            // 准备填充的数据
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("num", index);
            dataMap.put("kcmc", nbfbSixVo.getKcmc());
            dataMap.put("dw", nbfbSixVo.getDw());

            // 填充数据
            excelWriter.fill(dataMap, writeSheet);

            // 填充额外的数据
            excelWriter.fill(new FillWrapper(nbfbSixVo.getKcdgmtjList()), fillConfig, writeSheet);
        }

        try {
            // 完成写入
            excelWriter.finish();
            // 关闭资源
            baos.close();
            inputStream.close();
            templateStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}

